//
//  ServicePanelColorLight.swift
//  home
//
//  Created by Yun Zeng on 2019/8/27.
//  Copyright © 2019 Yun Zeng. All rights reserved.
//

import UIKit

class ServicePanelLightHue: ServicePanelBase {
    
    // b亮度百分比控制
    lazy private var brightnessView: HueBrightnessView = {
        let view = HueBrightnessView(frame: .zero)
        view.translatesAutoresizingMaskIntoConstraints = false
        view.heightAnchor.constraint(equalToConstant: 343).isActive = true
        view.widthAnchor.constraint(equalToConstant: 123).isActive = true
        view.backgroundColor = UIColor.clear
        return view
    } ()
    
    // 常用颜色选中框
    private lazy var favoriteRadios: FavoriteColorView = {
        let view = FavoriteColorView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 124))
        view.translatesAutoresizingMaskIntoConstraints = false
        
        view.heightAnchor.constraint(equalToConstant: 124).isActive = true
        view.widthAnchor.constraint(equalToConstant: 190).isActive = true
        view.backgroundColor = UIColor.clear
        return view
    } ()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view.backgroundColor = UIColor(hex: "dedede")
        
        // 亮度控制
        self.view.addSubview(brightnessView)
        brightnessView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        brightnessView.topAnchor.constraint(equalTo: self.customBar.bottomAnchor, constant: 45).isActive = true
        brightnessView.percentage = self.light.level.value?.toValueInt() ?? 0
        brightnessView.fillColor = UIColor(hex: self.light.colorValue)
        
        // 常用颜色颜色控制
        self.view.addSubview(self.favoriteRadios)
        favoriteRadios.topAnchor.constraint(equalTo: brightnessView.bottomAnchor, constant: 58).isActive = true
        favoriteRadios.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
        self.updateService()
        
        favoriteRadios.onColor = { (color, edit) in
            self.brightnessView.fillColor = color
 
            if edit == false {
                self.light.setColor(color: color.toHexString)
            } else {
                let storyboard = UIStoryboard(name: "Main", bundle: nil)
                 let controller = storyboard.instantiateViewController(withIdentifier: "ServiceColorEditControllerID") as! ServiceColorEditController
                 
                controller.light = self.light
                 controller.modalPresentationStyle = .formSheet
                 controller.isModalInPresentation = false
                controller.preferredContentSize = CGSize(width: 375, height: 680)
                self.present(controller, animated: true)
            }
        }
        
        brightnessView.onProgress = { percentage in
            self.light.setLevel(percentage: percentage)
        }
    }
    
    override func updateService() {
        
        if self.light.onState == .off {
            brightnessView.percentage = 0
        } else {
            brightnessView.percentage = self.light.level.value?.toValueInt() ?? 0
        }
        
        brightnessView.fillColor = UIColor(hex: self.light.colorValue)
        self.customBar.subtitle = self.light.desc
        self.favoriteRadios.setColor(color: self.light.colorValue)
    }
    
    
    var light: ServiceLightHue
    init(light: ServiceLightHue) {
        self.light = light
        super.init(service: light.service)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

// MARK: 亮度控制
class HueBrightnessView: UIView {
    // 背景颜色
    let bgColor = UIColor(hex: "EBEBEB")
    // 填充颜色
    var fillColor = UIColor(hex: "98FBB2") {
        didSet {
            self.setNeedsDisplay()
        }
    }
    
    var percentage: Int = 0 {
        didSet {
            self.height = Int(343 * self.percentage / 100)
        }
    }
    
    var onProgress: ((_ percentage: Int) -> Void)?
    private var height: Int = 0 {
        didSet {
            UIView.animate(withDuration: 0.5) {
                self.setNeedsDisplay()
            }
        }
    }
    
    override func draw(_ rect: CGRect) {
        // General Declarations
        let context = UIGraphicsGetCurrentContext()!
        // Group 3
        context.saveGState()
        context.beginTransparencyLayer(auxiliaryInfo: nil)

        // Clip Clip
        let clipPath = UIBezierPath()
        clipPath.move(to: CGPoint(x: 30, y: 343))
        clipPath.addLine(to: CGPoint(x: 94, y: 343))
        clipPath.addCurve(to: CGPoint(x: 124, y: 313), controlPoint1: CGPoint(x: 110.57, y: 343), controlPoint2: CGPoint(x: 124, y: 329.57))
        clipPath.addLine(to: CGPoint(x: 124, y: 30))
        clipPath.addCurve(to: CGPoint(x: 94, y: 0), controlPoint1: CGPoint(x: 124, y: 13.43), controlPoint2: CGPoint(x: 110.57, y: 0))
        clipPath.addLine(to: CGPoint(x: 30, y: 0))
        clipPath.addCurve(to: CGPoint(x: 0, y: 30), controlPoint1: CGPoint(x: 13.43, y: 0), controlPoint2: CGPoint(x: 0, y: 13.43))
        clipPath.addLine(to: CGPoint(x: 0, y: 313))
        clipPath.addCurve(to: CGPoint(x: 30, y: 343), controlPoint1: CGPoint(x: 0, y: 329.57), controlPoint2: CGPoint(x: 13.43, y: 343))
        clipPath.close()
        clipPath.usesEvenOddFillRule = true
        clipPath.addClip()

        // Rectangle Drawing
        let rectanglePath = UIBezierPath(rect: CGRect(x: 0, y: 0, width: 124, height: 343))
        bgColor.setFill()
        rectanglePath.fill()

        // Rectangle 2 Drawing
        let rectangle2Path = UIBezierPath(rect: CGRect(x: 0, y: 343-self.height, width: 124, height: self.height))
        fillColor.setFill()
        rectangle2Path.fill()

        context.endTransparencyLayer()
        context.restoreGState()
    }
        
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        let point = touches.first!.preciseLocation(in: self)
        self.moveTo(point: point, state: .began)
        UIView.animate(withDuration: 0.1) {
            self.transform = CGAffineTransform(scaleX: 1.03, y: 1.03)
        }
    }
    
    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        let point = touches.first!.preciseLocation(in: self)
        self.moveTo(point: point, state: .moved)
    }
    
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        let point = touches.first!.preciseLocation(in: self)
        self.moveTo(point: point, state: .ended)
        UIView.animate(withDuration: 0.1) {
            self.transform = .identity
        }
    }
    
    enum moveState: Int {
        case began
        case moved
        case ended
    }
    
    func moveTo(point: CGPoint, state: moveState = .moved) {
        if point.y > 0 && point.y < 343 {
            self.height = 343 - Int(point.y)
        } else if point.y < 0 {
            self.height = 343
        } else {
            self.height = 0
        }
        
        let percentage = Int(self.height * 100 / 343)
        if state == .moved {
            return
        }
        self.onProgress?(percentage)
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        // 捕捉下滑返回手势
        let gesture = UIPanGestureRecognizer(target: nil, action: nil)
        gesture.cancelsTouchesInView = false
        self.addGestureRecognizer(gesture)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

// MARK: 常用颜色选项
class FavoriteColorView: UIView {
    class ColorView: UIView {
        var colorView: UIView!
        var forceView: UIView!
        
        var editLabel: UILabel!
        
        var color: UIColor = UIColor.white {
            didSet {
                self.colorView.backgroundColor = self.color
                let hsba = color.hsba
                // 黄色hue: 30~76
                if (hsba.hue > 30 && hsba.hue < 76) || hsba.saturation < 50 {
                    self.forceView.layer.borderColor = UIColor.gray.cgColor
                    let attributes: [NSAttributedString.Key : Any] = [
                        NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.bold),
                        NSAttributedString.Key.kern: -0.36,
                        NSAttributedString.Key.foregroundColor: UIColor.gray]
                    self.editLabel.attributedText = NSAttributedString(string: "编辑", attributes: attributes)
                    
                } else {
                    self.forceView.layer.borderColor = UIColor.white.cgColor
                    let attributes: [NSAttributedString.Key : Any] = [
                        NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.bold),
                        NSAttributedString.Key.kern: -0.36,
                        NSAttributedString.Key.foregroundColor: UIColor.white]
                    self.editLabel.attributedText = NSAttributedString(string: "编辑", attributes: attributes)
                }
                
                Logger.Info("\(hsba)")
            }
        }
        
        init(frame: CGRect, color: UIColor) {
            super.init(frame: frame)
            let colorRect = CGRect(x: 0, y: 0, width: frame.width, height: frame.height)
            self.colorView = UIView(frame: colorRect)
            self.colorView.backgroundColor = color
            
            self.colorView.layer.cornerRadius = self.colorView.frame.width  / 2
            
            self.forceView = UIView(frame: CGRect(x: 4, y: 4, width: colorRect.width - 8, height: colorRect.height - 8))
            forceView.layer.cornerRadius = (colorRect.width - 6) / 2
            forceView.layer.borderColor = CGColor(srgbRed: 1, green: 1, blue: 1, alpha: 1)
            forceView.layer.borderWidth = 2.5
            
            editLabel = UILabel(frame: CGRect(x: 0, y: 0, width: colorRect.width - 8, height: colorRect.height - 8))
            let attributes: [NSAttributedString.Key : Any] = [
                NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.bold),
                NSAttributedString.Key.kern: -0.36,
                NSAttributedString.Key.foregroundColor: UIColor.white]
            editLabel.attributedText = NSAttributedString(string: "编辑", attributes: attributes)
            editLabel.textAlignment = NSTextAlignment.center
            forceView.addSubview(editLabel)
            
            self.addSubview(self.colorView)
            self.addSubview(self.forceView)
            self.color = color
            self.forceView.layer.opacity = 0
        }
        
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
        
        var forced: Bool = false {
            didSet {
                if self.forced {
                    self.forceView.layer.opacity = 1
                } else {
                    self.forceView.layer.opacity = 0
                }
            }
        }
        
        var onForced: ((_ color: UIColor, _ isEdit: Bool) -> Void)?
        override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
            print("color: \(self.color.toHexString)")
            self.onForced?(self.color, self.forced)
        }
    }
    
    fileprivate let colors = ["F1A252", "87D13F", "3478F7", "E633C7", "EA414A", "9B20F3"]
    fileprivate var cells = [ColorView]()
    
    func setColor(color: String) {
        var index: Int?
        for i in 0 ..< self.colors.count {
            if self.colors[i] == color {
                cells[i].forced = true
                if index == nil {
                    index = i
                }
            } else {
                cells[i].forced = false
            }
        }
        if index == nil || index! == colors.count - 1 {
            cells.last!.forced = true
            cells.last!.color = UIColor(hex: color)
        } else {
            cells.last!.forced = false
            cells.last!.color = UIColor(hex: colors.last!)
        }
    }
    
    var onColor: ((_ color: UIColor, _ edit: Bool) -> Void)?
    override init(frame: CGRect) {
        super.init(frame: frame)
        for index in 0 ..< self.colors.count {
            let frame = CGRect(x: 68 * (index % 3), y: Int(index / 3) * 63, width: 56, height: 56)
            let color = UIColor(hex: self.colors[index])
            let cell = ColorView(frame: frame, color: color)
            self.addSubview(cell)
            self.cells.append(cell)
        }
        
        for index in 0 ..< self.colors.count {
            cells[index].onForced = { (color, edit) in
                self.onColor?(color, edit)
                for i in 0 ..< self.colors.count {
                    if i == index {
                        self.cells[i].forced = true
                    } else {
                        self.cells[i].forced = false
                    }
                }
            }
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}










